package com.hudsonmq.spring.impl.produce.helper;

import com.hudson.common.domain.meta.TopicQueueMap;
import com.hudsonmq.spring.domain.produce.TopicQueueInfo;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: 渔小鲤
 * @DateTime: 2025/7/27 1:57
 **/
public class TopicQueueHelper {
    public static ConcurrentHashMap<String, List<TopicQueueInfo>> TOPIC_QUEUE_MAP = new ConcurrentHashMap<>();
    private static final Set<String> BROKER_TOPIC_SET = new CopyOnWriteArraySet<>();

    public static void changeTopicQueue(TopicQueueMap topicQueueMap) {
        String brokerName = topicQueueMap.getBrokerName();
        for (Map.Entry<String, Integer> entry : topicQueueMap.getQueueNumMap().entrySet()) {
            if (!BROKER_TOPIC_SET.contains(brokerName + entry.getKey())) {
                for (int i = 0; i < entry.getValue(); i++) {
                    TOPIC_QUEUE_MAP.computeIfAbsent(entry.getKey(), k -> new CopyOnWriteArrayList<>())
                            .add(new TopicQueueInfo(brokerName, entry.getKey(), i));
                    BROKER_TOPIC_SET.add(brokerName + entry.getKey());
                }
            }
        }
    }

    public static TopicQueueInfo getTopicQueue(String topic, Integer index) {

        List<TopicQueueInfo> topicQueueInfos = TOPIC_QUEUE_MAP.get(topic);
        if(topicQueueInfos == null || topicQueueInfos.isEmpty()){
            // todo: 控制处理
            // 此时还没初始化，所以返回null 系统暂存一下在发起;
            return null;
        }
        return topicQueueInfos.get(index % topicQueueInfos.size());
    }
}
